<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;
use App\Models\Coupon;
use App\Models\CouponType;
use Exception;

class GenerateCoupons extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'GenerateCoupons {--N|number=} {--Code|card_type=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $number = intval($this->option('number'));

        if ($number == 0) {
            $number = intval($this->ask('请输入需要生成的优惠劵条数?'));
        }

        if ($number == 0 || $number > 1000000) {
            $this->info('输入不合法，程序结束。');
            return 0;
        }

        // 清除之前的优惠券
        // Coupon::where('status', 0)->delete();

        $card_type = $this->option('card_type');
        $couponType = CouponType::where('code', $card_type)->first();
        if (!$couponType) {
            $this->info('输入的card_type不存在，程序结束。');
            return 0;
        }

        $batchNumber = date("ymd") . Str::random(4);
        $this->info("正在生成 " . $number . " 张优惠劵, 批次为 " . $batchNumber . " ...");

        $success = 0;
        $failed = 0;
        while (($success + $failed) < $number) {
            try {
                Coupon::create([
                    'code' => Str::random(8),
                    'batch_code' => $batchNumber,
                    'card_type' => $card_type,
                    'price' => $couponType->price
                ]);
                $success++;
            } catch (Exception $e) {
                $failed++;
                $this->info($e->getMessage());
            }
        }

        $this->info($number . " 张优惠劵生成成功。");

        return 0;
    }
}
